package com.lerays.spider.sougou.handler;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.List;

import org.lionsoul.websnail.json.JSONArray;
import org.lionsoul.websnail.json.JSONObject;

import com.lerays.spider.sougou.SpiderHttpServer;
import com.lerays.spider.sougou.hack.Session;
import com.lerays.spider.sougou.hack.SessionFactory;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * session list request handler.
 * 
 * @author chenxin<chenxin619315@gmail.com>
 */
public class SessionListRequestHandler implements HttpHandler
{
	private SpiderHttpServer httpServer = null;
	
	public SessionListRequestHandler( SpiderHttpServer httpServer )
	{
		this.setHttpServer(httpServer);
	}

	@Override
	public void handle(HttpExchange e) throws IOException 
	{
		JSONObject json = new JSONObject();
		
		SessionFactory sessionFactory = httpServer.getsougouSpider().getSessionFactory();
		List<Session> sessionList = sessionFactory.getList();
		
		json.put("errno", 0);						//status
		json.put("count", sessionList.size());		//count
		JSONArray sessions = new JSONArray();		//sessions
		
		synchronized ( sessionList )
		{	
			Iterator<Session> it = sessionList.iterator();
			while ( it.hasNext() )
			{
				Session sess = it.next();
				JSONObject item = new JSONObject();
				item.put("validate", sess.getValidate());
				
				//unicode encode the username
				/*StringBuilder sb = new StringBuilder();
				for ( int i = 0; i < sess.getUsername().length(); i++ )
				{
					sb.append("\\u");
					sb.append(Integer.toHexString(sess.getUsername().charAt(i)));
				}*/
				
				item.put("username", sess.getUsername());
				item.put("refererUrl", sess.getRefererUrl());
				item.put("checkUrl", sess.getCheckUrl());
				item.put("syncUrl", sess.getSyncUrl());
				item.put("cookies", sess.getCookies());
				item.put("userAgent", sess.getUserAgent());
				
				//System.out.println(item.toString());
				sessions.put(item);
			}
		}
		
		json.put("list", sessions);
		
		//send the http response
		String ret = new String(json.toString().getBytes("UTF-8"), "ISO-8859-1");
		e.sendResponseHeaders(HttpURLConnection.HTTP_OK, ret.length());
		OutputStream os = e.getResponseBody();
		os.write(ret.getBytes("ISO-8859-1"));
		os.close();
		e.close();
		//let gc do its work
		json = null;
	}

	public SpiderHttpServer getHttpServer() 
	{
		return httpServer;
	}

	public void setHttpServer(SpiderHttpServer httpServer) 
	{
		this.httpServer = httpServer;
	}
	
}
